package com.iwop.moto.utils.stringUtil;


import com.iwop.moto.model.SuperRecordModel;
import org.apache.htrace.fasterxml.jackson.core.JsonParser;
import org.apache.htrace.fasterxml.jackson.core.JsonProcessingException;
import org.apache.htrace.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.*;

public class JsonUtils {

    /**
     * json字符串转集合类型
     */
    public static List<SuperRecordModel> jsonToList (String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        List<LinkedHashMap<String, Object>> list = mapper.readValue(json, List.class);
        List<SuperRecordModel> lsMap = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            Set<String> set = map.keySet();
            Iterator<String> iter = set.iterator();
            SuperRecordModel mapResult = new SuperRecordModel();
            while (iter.hasNext()) {
                String field = iter.next();
                mapResult.put(field, map.get(field));
            }
            lsMap.add(mapResult);
        }
        return lsMap;
    }

    /**
     * Json字符串转Map
     */
    public static Map<String, Map<String, Object>> toMap(String json) throws
            IOException {
        try{
            return new ObjectMapper().readValue(json, Map.class);
        } catch (Exception e){
            //e.printStackTrace();
            return new HashMap<String, Map<String, Object>>();
        }
    }

    /**
     * 对象转Json字符串
     */
    public static String toJsonString(Object obj){
        ObjectMapper mapper = new ObjectMapper();
        String  str = "";
        try {
            str =  mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * @功能: json 字符串转 JavaBean
     * @日期: liuwb by 2016-10-13 18:58:58 create
     * @param json json 字符串
     * @param cls  JavaBean实体对象
     */
    public static <T> T jsonToBean(String json , Class<T> cls) {
        try{
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES , true);
            return mapper.readValue(json, cls);
        } catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
